import { intersectionWith, isEqual, mergeWith, unionWith } from "lodash-es";
import { isArray, isObject } from "@/utils/is";
import { FC } from "react";

// dynamic use hook props
export function getDynamicProps<T extends Record<string, unknown>, U>(props: T): Partial<U> {
	const ret: Recordable = {};

	// eslint-disable-next-line array-callback-return
	Object.keys(props).map(key => {
		ret[key] = (props as Recordable)[key].current;
	});

	return ret as Partial<U>;
}

/**
 * Recursively merge two objects.
 * 递归合并两个对象。
 *
 * @param source The source object to merge from. 要合并的源对象。
 * @param target The target object to merge into. 目标对象，合并后结果存放于此。
 * @param mergeArrays How to merge arrays. Default is "replace".
 *        如何合并数组。默认为replace。
 *        - "union": Union the arrays. 对数组执行并集操作。
 *        - "intersection": Intersect the arrays. 对数组执行交集操作。
 *        - "concat": Concatenate the arrays. 连接数组。
 *        - "replace": Replace the source array with the target array. 用目标数组替换源数组。
 * @returns The merged object. 合并后的对象。
 */
export function deepMerge<T extends object | null | undefined, U extends object | null | undefined>(
	source: T,
	target: U,
	mergeArrays: "union" | "intersection" | "concat" | "replace" = "replace"
): T & U {
	if (!target) return source as T & U;

	if (!source) return target as T & U;

	return mergeWith({}, source, target, (sourceValue, targetValue) => {
		if (isArray(targetValue) && isArray(sourceValue)) {
			switch (mergeArrays) {
				case "union":
					return unionWith(sourceValue, targetValue, isEqual);
				case "intersection":
					return intersectionWith(sourceValue, targetValue, isEqual);
				case "concat":
					return sourceValue.concat(targetValue);
				case "replace":
					return targetValue;
				default:
					throw new Error(`Unknown merge array strategy: ${mergeArrays as string}`);
			}
		}
		if (isObject(targetValue) && isObject(sourceValue)) return deepMerge(sourceValue, targetValue, mergeArrays);

		return undefined;
	});
}

/**
 * Add the object as a parameter to the URL
 * @param baseUrl url
 * @param obj
 * @returns {string}
 * eg:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
export function setObjToUrlParams(baseUrl: string, obj: any): string {
	let parameters = "";
	for (const key in obj) parameters += `${key}=${encodeURIComponent(obj[key])}&`;

	parameters = parameters.replace(/&$/, "");
	return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, "?") + parameters;
}

type Func = (...args: any[]) => void;
// 防抖函数
export function debounce<T extends Func>(fn: T, delay: number): T {
	let time: NodeJS.Timeout;
	return function (this: any, ...args: Parameters<T>) {
		clearTimeout(time);
		time = setTimeout(() => {
			fn.apply(this, args);
		}, delay);
	} as any;
}

export function nextTick(callback?: Function) {
	return new Promise<void>(resolve => {
		setTimeout(() => {
			callback && callback();
			resolve();
		}, 0);
	});
}
/*=============== */

interface EventShim {
	new (...args: any[]): {
		$props: {
			onClick?: (...args: any[]) => void;
		};
	};
}

export type WithInstall<T> = T & {
	install(app: any): void;
} & EventShim;

export type CustomComponent = FC & { displayName?: string };

export function withInstall<T extends CustomComponent>(component: T, alias?: string) {
	(component as Record<string, unknown>).install = (app: any) => {
		const compName = component.displayName || component.name;
		if (!compName) return;
		if (alias && app.context?.addGlobalProperty) {
			app.context.addGlobalProperty(alias, component);
		}
	};

	return component as WithInstall<T>;
}
// ========== ERP 专属方法 ==========

const ERP_COUNT_DIGIT = 3;
const ERP_PRICE_DIGIT = 2;
/**
 * 【ERP】格式化数量，保留三位小数
 *
 * 例如说：库存数量
 *
 * @param num 数量
 * @return 格式化后的数量
 */
/**
 * 【ERP】格式化 Input 数字
 *
 * 例如说：库存数量
 *
 * @param num 数量
 * @package digit 保留的小数位数
 * @return 格式化后的数量
 */
export const erpNumberFormatter = (num: number | string | undefined, digit: number) => {
	if (num == null) {
		return "";
	}
	if (typeof num === "string") {
		num = parseFloat(num);
	}
	// 如果非 number，则直接返回空串
	if (isNaN(num)) {
		return "";
	}
	return num.toFixed(digit);
};
export const erpCountInputFormatter = (num: number | string | undefined) => {
	return erpNumberFormatter(num, ERP_COUNT_DIGIT);
};
/**
 * 【ERP】格式化金额，保留二位小数
 *
 * 例如说：库存数量
 *
 * @param num 数量
 * @return 格式化后的数量
 */
export const erpPriceInputFormatter = (num: number | string | undefined) => {
	return erpNumberFormatter(num, ERP_PRICE_DIGIT);
};
/**
 * 【ERP】价格计算，四舍五入保留两位小数
 *
 * @param price 价格
 * @param count 数量
 * @return 总价格。如果有任一为空，则返回 undefined
 */
export const erpPriceMultiply = (price: number, count: number) => {
	if (price == null || count == null) {
		return undefined;
	}
	return parseFloat((price * count).toFixed(ERP_PRICE_DIGIT));
};
/**
 * 数组求和
 *
 * @param values 数字数组
 * @return 求和结果，默认为 0
 */
export const getSumValue = (values: number[]): number => {
	return values.reduce((prev, curr) => {
		const value = Number(curr);
		if (!Number.isNaN(value)) {
			return prev + curr;
		} else {
			return prev;
		}
	}, 0);
};

// 获取URL上所有参数
export const getUrlParams = (url: string) => {
	// 通过 ? 分割获取后面的参数字符串
	let urlStr = url.split("?")[1];
	// 创建空对象存储参数
	let obj: Recordable = {};
	// 再通过 & 将每一个参数单独分割出来
	let paramsArr = urlStr.split("&");
	for (let i = 0, len = paramsArr.length; i < len; i++) {
		// 再通过 = 将每一个参数分割为 key:value 的形式
		let arr = paramsArr[i].split("=");
		obj[arr[0]] = arr[1];
	}
	return obj;
};
